package com.keyancompany.zhongbaopingtai.api;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.ZBApplication;
import com.keyancompany.zhongbaopingtai.activity.LoginActivity;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * http请求基类，get post 上传文件等
 *
 * @author pengtao_H
 */
public class BaseAPI {

    private static final String TAG = "BaseAPI";
    public static final int DETAULT_COUNT = 20;

    // Create a new AsyncHttpClient instance and make a request:
    private static AsyncHttpClient client = new AsyncHttpClient();

    /**
     * @param url            请求地址
     * @param params         请求参数
     * @param handler        网络请求回调
     * @param type           请求的类型一般适用于一个界面多个请求返回
     * @param loadingHandler 在baseActivity中的加载dialog,如果不需要则可以为空
     */
    protected static void get(String url, RequestParams params,
                              final IAsyncHttpResponseHandler handler, final int type,
                              final Handler loadingHandler) {
        client.get(url, params, new BaseAsyncHttpResponseHandler(handler, type,
                loadingHandler));
    }

    protected static void get(String url,
                              final IAsyncHttpResponseHandler handler, final int type,
                              final Handler loadingHandler) {
        client.get(url, new BaseAsyncHttpResponseHandler(handler, type,
                loadingHandler));
    }

//    protected static void post(String url,
//                               final IAsyncHttpResponseHandler handler, final int type,
//                               final Handler loadingHandler) {
//        client.post(url, new BaseAsyncHttpResponseHandler(handler, type,
//                loadingHandler));
//    }

    protected static void post(String url, RequestParams params,
                               final IAsyncHttpResponseHandler handler, final int type,
                               final Handler loadingHandler) {

        client.post(url, params, new BaseAsyncHttpResponseHandler(handler,
                type, loadingHandler));
    }


//    /**
//     * 带参数的上传 文件转成io流,还可以转成byte 或者以File形式 详情参见 <br>
//     * http://loopj.com/android-async-http/
//     *
//     * @param url
//     * @param params
//     * @param handler
//     */
//    protected static void uploadFile(String url, RequestParams params,
//                                     File file, String fileName,
//                                     final IAsyncHttpResponseHandler handler, final int type,
//                                     final Handler loadingHandler) {
//        FileInputStream myInputStream;
//        try {
//            myInputStream = new FileInputStream(file);
//            // params.put(arg0, arg1);//key--value
//            params.put("secret_passwords", myInputStream, fileName);
//            // params.put("secret_passwords", myInputStream, "passwords.txt");
//
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        client.put(url, params, new BaseAsyncHttpResponseHandler(handler, type,
//                loadingHandler));
//    }


    protected static void uploadFile(String url, RequestParams params,
                                     final IAsyncHttpResponseHandler handler, final int type,
                                     final Handler loadingHandler) {
//        FileInputStream myInputStream;
//        try {
//            myInputStream = new FileInputStream(file);
//            byte[] byt = new byte[myInputStream.available()];
//            myInputStream.read(byt);

//            params.put("Filedata", file);
//
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        client.post(url, params, new BaseAsyncHttpResponseHandler(handler, type,
                loadingHandler));
    }


    /**
     * 判断token值是否过期
     *
     * @param arg0
     * @return
     */
    protected static boolean isTimeOutAboutToken(String arg0) {
        try {
            JSONObject job = JSON.parseObject(arg0);
        } catch (Exception e) {
            return false;
        }
        // if (job.getIntValue("code") == Constants.TIME_OUT_CODE) { // TOKEN
        // // 过期
        // JumpMain();
        // return true;
        // }
        return false;
    }

    protected static void JumpMain() {
        Context context = ZBApplication.getInstance();
        Intent it = new Intent(context, LoginActivity.class);
        it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(it);
        // ((Activity) context).finish();
    }


    public static HashMap bySortCompare(HashMap params) {

        List<Map.Entry<String, String>> list_Data = new ArrayList<Map.Entry<String, String>>(params.entrySet());
        Collections.sort(list_Data, new Comparator() {
            public int compare(Object o1, Object o2) {
                Map.Entry obj1 = (Map.Entry) o1;
                Map.Entry obj2 = (Map.Entry) o2;
                return (obj1.getKey()).toString().compareTo(obj2.getKey().toString());
            }
        });
        params.clear();
        HashMap linkMap = new LinkedHashMap();
//		Log.e("Sign", ":-------------------------list_data :" + list_Data.toString());
        StringBuffer buffer = new StringBuffer();
        for (Map.Entry<String, String> item : list_Data) {
            if (item.getValue() == null) {
                linkMap.put(item.getKey(), "");
                buffer.append(item.getKey()).append("");
            } else {
                linkMap.put(item.getKey(), item.getValue());
                buffer.append(item.getKey()).append(item.getValue());
            }
        }
//		Log.e("Sign", ":-------------------------map :" + JSONObject.toJSONString(linkMap, false));

//		System.out.println(linkMap.toString());
        String jsonString = JSONObject.toJSONString(linkMap, false);
        linkMap = null;
        params.put("json", jsonString);
        params.put("md5", buffer.toString());
        return params;
    }

    protected static class BaseAsyncHttpResponseHandler extends
            AsyncHttpResponseHandler {
        private IAsyncHttpResponseHandler handler;
        private int type;
        private Handler loadingHandler;

        public BaseAsyncHttpResponseHandler(IAsyncHttpResponseHandler handler,
                                            int type, Handler loadingHandler) {
            super();
            this.handler = handler;
            this.type = type;
            this.loadingHandler = loadingHandler;
        }

        @Override
        public void onFailure(Throwable arg0, String arg1) {
            super.onFailure(arg0, arg1);
//            L.d(TAG, arg1);
            if (loadingHandler != null) {
                loadingHandler.sendEmptyMessage(Constants.CANCLE_DIALOG);
            }
            if (handler != null)
                handler.failed(arg1);
        }

        @Override
        public void onFinish() {
            super.onFinish();
            if (loadingHandler != null) {
                loadingHandler.sendEmptyMessage(Constants.CANCLE_DIALOG);
            }
            if (handler != null)
                handler.finish(type);
        }

        @Override
        public void onStart() {
            super.onStart();
            if (loadingHandler != null) {
                loadingHandler.sendEmptyMessage(Constants.CREATE_DIALOG);
            }
            if (handler != null)
                handler.start(type);
        }

        @Override
        public void onSuccess(String arg0) {
            super.onSuccess(arg0);
//            L.d(TAG, arg0);
            if (loadingHandler != null) {
                loadingHandler.sendEmptyMessage(Constants.CANCLE_DIALOG);
            }
            if (isTimeOutAboutToken(arg0)) {
                return;
            }

            if (handler != null)
                handler.success(type, arg0);
        }

    }
}
